package com.hongye.broker.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.hongye.broker.feign.CustomerFeignService;
import com.hongye.broker.mapper.MessageMapper;
import com.hongye.broker.service.MessageService;
import com.hongye.broker.vo.MessageVo;
import com.hongye.common.entity.CustomerEntity;
import com.hongye.common.entity.MessageEntity;
import com.hongye.common.exception.ServiceException;
import com.hongye.common.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private CustomerFeignService customerFeignService;


    @Override
    public ResponseResult delete(Integer messageId) {

        try {
            if (messageId.intValue()==0){
                throw new ServiceException("401","参数为空");
            }
            messageMapper.delete(messageId);
            return new ResponseResult(1,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return new ResponseResult(-1,"删除失败");
        }
    }

    @Override
    public ResponseResult update(Integer integer) {
        MessageEntity messageEntity = messageMapper.findById(integer);
        if (ObjectUtil.isNull(messageEntity)){
            throw new ServiceException("401","参数错误");
        }
        //修改
        messageMapper.update(integer);
        return ResponseResult.ok(1,"顶置成功",new HashMap<String, Object>());
    }



    @Override
    public ResponseResult list(int brokerId) {
        List<MessageEntity> list = messageMapper.list(brokerId);
        ArrayList<MessageVo> messageVos = new ArrayList<>();
        list.stream().forEach(messageEntity -> {
            MessageVo item = new MessageVo();
            BeanUtils.copyProperties(messageEntity,item);
            //查询用户姓名
            CustomerEntity customerFindByIdById = customerFeignService.findById(messageEntity.getCustomerId());
            item.setCustomerName(customerFindByIdById.getCustomerName());
            //赋值
            messageVos.add(item);
        });

        HashMap<String, Object> map = new HashMap<>();
        map.put("lsit",messageVos);
        return ResponseResult.ok(1,"成功",map);
    }
}
